import React, { useState, useRef, useCallback, useEffect } from "react";
import { X } from "lucide-react";
import VariableReferenceGuide from "./VariableReferenceGuide";

const DraggableVariableGuide = ({ isVisible, onClose, onInsertVariable }) => {
  const [position, setPosition] = useState(() => {
    if (typeof window !== "undefined") {
      const initialX = Math.max(0, (window.innerWidth - 450) / 2);
      const initialY = Math.max(0, (window.innerHeight - 600) / 2);
      return { x: initialX, y: initialY };
    }
    return { x: 50, y: 50 };
  });
  const [isDragging, setIsDragging] = useState(false);
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const windowRef = useRef(null);

  const handleMouseDown = (e) => {
    if (e.target.closest(".variable-guide-content")) return;
    setIsDragging(true);
    setDragStart({ x: e.clientX - position.x, y: e.clientY - position.y });
  };

  const handleMouseMove = useCallback(
    (e) => {
      if (!isDragging) return;
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const windowWidth = windowRef.current?.offsetWidth || 450;
      const windowHeight = windowRef.current?.offsetHeight || 600;
      const maxX = viewportWidth - windowWidth;
      const maxY = viewportHeight - windowHeight;

      setPosition({
        x: Math.max(0, Math.min(e.clientX - dragStart.x, maxX)),
        y: Math.max(0, Math.min(e.clientY - dragStart.y, maxY)),
      });
    },
    [isDragging, dragStart]
  );

  const handleMouseUp = () => setIsDragging(false);

  useEffect(() => {
    if (isDragging) {
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);
      return () => {
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };
    }
  }, [isDragging, handleMouseMove]);

  if (!isVisible) return null;

  return (
    <div
      ref={windowRef}
      className="fixed bg-white border border-gray-300 rounded-lg shadow-2xl z-[9999] flex flex-col"
      style={{
        left: position.x,
        top: position.y,
        width: "450px",
        height: "600px",
        cursor: isDragging ? "grabbing" : "default",
      }}
    >
      <div
        className="flex items-center justify-between p-3 bg-gray-50 border-b rounded-t-lg cursor-grab active:cursor-grabbing select-none"
        onMouseDown={handleMouseDown}
      >
        <h3 className="text-base font-semibold text-gray-800 flex items-center gap-2">
          📖 变量参考手册
          <span className="text-xs text-gray-500">(可拖拽移动)</span>
        </h3>
        <button
          onClick={onClose}
          className="w-6 h-6 rounded-full bg-red-500 hover:bg-red-600 text-white text-xs flex items-center justify-center transition-colors"
          title="关闭"
        >
          <X size={14} />
        </button>
      </div>
      <div className="variable-guide-content flex-1 overflow-hidden">
        <VariableReferenceGuide onInsertVariable={onInsertVariable} />
      </div>
    </div>
  );
};

export default DraggableVariableGuide;
